package cn.tedu.weibo.service.impl;

import cn.tedu.weibo.common.response.JsonResult;
import cn.tedu.weibo.common.response.StatusCode;
import cn.tedu.weibo.exception.ServiceException;
import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDTO;
import cn.tedu.weibo.pojo.dto.UserRegDTO;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVO;
import cn.tedu.weibo.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService implements IUserService {
    @Autowired
    UserMapper mapper;
    @Override
    public void reg(UserRegDTO userRegDTO) {
        UserVO userVO = mapper.selectByUsername(userRegDTO.getUsername());
        if (userVO!=null){
            //三层架构中,在Service层不能直接给客户端响应数据,
            // 出现业务异常情况通过抛出自定义Service异常的方式在全局异常处理器中对异常进行捕获
            //并响应给客户端
            throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        mapper.insert(user);
    }

    @Autowired
    AuthenticationManager manager;

    @Override
    public void login(UserLoginDTO userLoginDTO) {
        //通过认证管理器启动Security的认证流程  返回认证结果对象
        Authentication result = manager.authenticate(new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUsername(), userLoginDTO.getPassword()));
        //将认证结果保存到Security上下文中   让Security框架记住登录状态
        SecurityContextHolder.getContext().setAuthentication(result);


//        UserVO userVO = mapper.selectByUsername(userLoginDTO.getUsername());
//        //没查到代表用户名错误
//        if (userVO==null){
//          throw new ServiceException(StatusCode.USERNAME_ERROR);
//        }
//        //密码不相等代表 密码错误
//        if (!userVO.getPassword().equals(userLoginDTO.getPassword())){
//            throw new ServiceException(StatusCode.PASSWORD_ERROR);
//        }
    }
}
